"""
$ sanic main:app --reload
"""
from sqlalchemy import INTEGER, Column, String, select, Integer, DateTime
from sqlalchemy.orm import declarative_base
from urllib.parse import quote

Base = declarative_base()
import sqlalchemy
print(sqlalchemy.__version__)


class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    create_time = Column(DateTime)
    username = Column(String(255))
    password = Column(String(500))



from sanic import Sanic, json
from sqlalchemy.ext.asyncio import create_async_engine
from contextvars import ContextVar
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import sessionmaker

app = Sanic("my_app")
url = f'mysql+aiomysql://{quote("root")}:{quote("baloneolike@x")}@localhost/test'
engine = create_async_engine(url, echo=False, future=True)

Session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

app.update_config({'KEEP_ALIVE_TIMEOUT': 70})
from asyncio import CancelledError

@app.route('/api/v1/data', methods=['GET'])
async def data(request):

    async with Session() as session:
        res = await session.execute(select(User).where(User.username == 'tom'))  # 都会自动开启隐士事物
        user: User = res.scalar_one_or_none()
        if user:
            return json({'name': user.username})

    return json({})

